#!/bin/sh

if pgrep pdns_server; then
    echo 'There are (stray?) pdns_servers running that might interfere with these tests!'
fi
if pgrep pdns_recursor; then
    echo 'There are (stray?) pdns_recursors running that might interfere with these tests!'
fi

export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python

if [ ! -d .venv ]; then
  python3 -m venv .venv
fi
. .venv/bin/activate
python -V
pip install -U pip | cat
pip install -r requirements.txt | cat

protoc -I=../pdns/ --python_out=. ../pdns/dnsmessage.proto
protoc -I=../pdns/ --python_out=. ../pdns/dnstap.proto


make clean-certs
make certs

mkdir -p configs

[ -f ./vars ] && . ./vars

export PDNS=${PDNS:-${PWD}/../pdns/pdns_server}
export PDNSUTIL=${PDNSUTIL:-${PWD}/../pdns/pdnsutil}
export PDNSRECURSOR=${PDNSRECURSOR:-${PWD}/../pdns/recursordist/pdns_recursor}
export RECCONTROL=${RECCONTROL:-${PWD}/../pdns/recursordist/rec_control}

LIBFAKETIME_DEFAULT=/usr/lib/$(arch)-linux-gnu/faketime/libfaketimeMT.so.1 # ubuntu default
LIBAUTHBIND_DEFAULT=/usr/lib/authbind/libauthbind.so.1
if [ $(uname -s) = "Darwin" ]; then
  # macOS is not /really/ supported here; it works for some tests, and then you might need sudo.
  LIBFAKETIME_DEFAULT=/usr/local/lib/faketime/libfaketime.1.dylib
  LIBAUTHBIND_DEFAULT=""
fi
if [ $(uname -s) = "OpenBSD" ]; then
  # OpenBSD is not /really/ supported here; it works for some tests, and then you might need sudo.
  LIBFAKETIME_DEFAULT=""
  LIBAUTHBIND_DEFAULT=""
fi

export LIBFAKETIME=${LIBFAKETIME:-$LIBFAKETIME_DEFAULT}
export LIBAUTHBIND=${LIBAUTHBIND:-$LIBAUTHBIND_DEFAULT}

export PREFIX=127.0.0

for bin in "$PDNS" "$PDNSUTIL" "$PDNSRECURSOR" "$RECCONTROL" "$LIBFAKETIME" "$LIBAUTHBIND"; do
  if [ -n "$bin" -a ! -e "$bin" ]; then
    echo "E: Required binary $bin not found. Please install the binary and/or edit ./vars."
    exit 1
  fi
done

set -e
if [ "${PDNS_DEBUG}" = "YES" ]; then
  set -x
fi

if ! "$PDNSRECURSOR" --version 2>&1 | grep Features | grep -q dnstap-framestream; then
  export NODNSTAPTESTS=1
fi

# Run with -m 'not external' to skip test that require external connectivity
# Run with -m 'not unreliable_on_gh' to skip tests that are unreliable on GitHUb
# Run with -m 'not (external or unreliable_on_gh)' to skip both categories

# LIBFAKETIME is only added to LD_PRELOAD by the pyton code when needed
if [ "${LIBASAN}" != "" -o "${LIBAUTHBIND}" != "" ]; then
LD_PRELOAD="${LIBASAN} ${LIBAUTHBIND}" pytest --junitxml=pytest.xml "$@"
else
pytest --junitxml=pytest.xml "$@"
fi
